import 'dart:convert';

import 'package:eplorex/im/im_sdk_client.dart';
import 'package:eplorex/im/message_frame.dart';
import 'package:eplorex/models/message/chat_message_type.dart' as types;
import 'package:eplorex/models/message/message_content.dart';
import 'package:eplorex/utils/im_util.dart';

import '../im/message_frame_type.dart';
import '../models/message/partial_text.dart';
import '../models/message/text_message.dart';
import '../models/user/user.dart';
import '../providers/user_context.dart';
import '../providers/user_session.dart';

typedef WebsocketMessageCallBack = void Function(dynamic message);

class WebsocketEventHandler {
  void onMessage(dynamic message) {
    MessageFrame messageFrame = MessageFrame.fromJson(jsonDecode(message));
    if (messageFrame.header?.type == MessageTypeEnum.message_down.value) {
      Map<String, dynamic> messageBody =
          jsonDecode(messageFrame.body as String);
      UserSession.instance
          .getUser(messageBody['senderId'])
          .then((value) => {_notifyMessage(messageBody, value)});
    }
  }

  void _notifyMessage(
    Map<String, dynamic> messageBody,
    User? value,
  ) {
    PartialText partialText = types.PartialText.fromJson(
        jsonDecode(messageBody['message'])['messageContent']);
    types.TextMessage textMessage = TextMessage.fromPartial(
        author: value ?? transfer(UserContext.cxt()!),
        id: messageBody['ts']?.toString() ??
            DateTime.now().microsecond.toString(),
        createdAt: DateTime.now().millisecondsSinceEpoch,
        partialText: partialText,
        messageContent: TextMessageContent.fromParams(partialText.text));
    IMSdkClient.onMessage(textMessage);
  }

  void onDone() {}

  void onError(Object error) {}
}
